package com.sk.weichat.ui.message;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.AttentionUser;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.User;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.xmpp.ListenerManager;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 移除粉丝界面
 * create by swy 2019-09-12
 */
public class TabFansEditActivity extends BaseActivity implements View.OnClickListener {

    private TextView mTvTitle;
    private ImageView mImgLeft;
    private TextView mTvRight;
    private static final int maxCount = 20;
    private int selectCount = 0;
    List<User> fansList = new ArrayList<>();
    public static final String fansListKey = "TabFansEditActivity_fansListKey";

    private BaseQuickAdapter<User, BaseViewHolder> adapter;

    public static final void startTabFansEditActivity(Activity activity, ArrayList<User> fansList, int requestCode) {
        Intent intent = new Intent(activity, TabFansEditActivity.class);
        intent.putParcelableArrayListExtra(fansListKey, fansList);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_fans_edit_layout);
        initActionBar();
        ArrayList<User> list = getIntent() != null ? getIntent().getParcelableArrayListExtra(fansListKey) : null;
        if (list != null) {
            fansList.addAll(list);
        }
        adapter = new BaseQuickAdapter<User, BaseViewHolder>(R.layout.row_sort_friend, fansList) {

            @Override
            protected void convert(BaseViewHolder holder, User item) {
                LinearLayout layout_row_sort = holder.getView(R.id.layout_row_sort);
                if (item.getUserId().equals(Friend.ID_SYSTEM_MESSAGE)) {
                    //系统好友，隐藏掉
                    layout_row_sort.setVisibility(View.GONE);
                } else {
                    layout_row_sort.setVisibility(View.VISIBLE);
                }
                ImageView avatar_img = holder.getView(R.id.avatar_img);
                TextView nick_name_tv = holder.getView(R.id.nick_name_tv);
                TextView roles = holder.getView(R.id.roles);
                holder.getView(R.id.catagory_title).setVisibility(View.GONE);
                AttentionUser friend = item.getFriends();

                if (friend.getUserId().equals(Friend.ID_SYSTEM_MESSAGE)) {
                    avatar_img.setImageResource(R.mipmap.ic_service);
                } else {
                    AvatarHelper.getInstance().displayAvatar(friend.getToUserId(), avatar_img, true);
                }

                // 昵称
                nick_name_tv.setText(!TextUtils.isEmpty(friend.getRemarkName()) ? friend.getRemarkName() : item.getNickName());
                //好友
                if (friend.getStatus() == Friend.STATUS_FRIEND) {
                    roles.setVisibility(View.VISIBLE);
                    roles.setBackgroundResource(R.drawable.bg_role_friend);
                    roles.setText(getString(R.string.friend));
                } else {
                    roles.setVisibility(View.GONE);
                }

                //头像不可点击
                avatar_img.setClickable(false);
                holder.getView(R.id.chat_msc).setVisibility(View.VISIBLE);
                ((CheckBox) holder.getView(R.id.chat_msc)).setChecked(item.isSelected());


                //item点击事件监听
                layout_row_sort.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int pos = fansList.indexOf(item);
                        //编辑删除状态
                        if (item.isSelected()) {
                            selectCount--;
                            item.setSelected(false);
                        } else {
                            if (selectCount >= maxCount) {
                                ToastUtil.showToast(mContext, getString(R.string.tips_max_count_remove_fans_one_time));
                                return;
                            }
                            selectCount++;
                            item.setSelected(true);
                        }
                        adapter.notifyItemChanged(pos);
                        updateRightTitle(selectCount);
                    }
                });
            }
        };
        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setAdapter(adapter);
        updateTitle();
        adjustEmpty();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                Intent intent = new Intent();
                intent.putParcelableArrayListExtra(fansListKey, (ArrayList<? extends Parcelable>) fansList);
                setResult(Activity.RESULT_OK, intent);
                finish();
                break;

            case R.id.tv_title_right:
                String ids = getSelectUserIDs();
                if (TextUtils.isEmpty(ids)) {
                    return;
                }
                removeFans(ids);
                break;

        }
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putParcelableArrayListExtra(fansListKey, (ArrayList<? extends Parcelable>) fansList);
        setResult(Activity.RESULT_OK, intent);
        super.onBackPressed();
    }


    private String getSelectUserIDs() {
        String ids = "";
        for (int i = 0; i < fansList.size(); i++) {
            if (fansList.get(i).isSelected()) {
                ids += fansList.get(i).getUserId() + ",";
            }
        }
        return ids;
    }

    private void initActionBar() {
        getSupportActionBar().hide();

        mTvTitle = findViewById(R.id.tv_title_center);
        // mTvTitle.setText("粉丝(" + coreManager.getSelf().getFansCount() + ")");
        mTvRight = findViewById(R.id.tv_title_right);
        mTvRight.setText("移除");
        mTvRight.setTextColor(ContextCompat.getColor(this, R.color.color_8873FE));
        mImgLeft = findViewById(R.id.iv_title_left);
        mImgLeft.setImageResource(R.mipmap.icon_closed);

        findViewById(R.id.iv_title_left).setOnClickListener(this);
        findViewById(R.id.tv_title_right).setOnClickListener(this);
    }

    public void updateTitle() {
        mTvTitle.setText("粉丝(" + (fansList.size() - 1) + ")");
    }

    public void updateRightTitle(int count) {
        if (count == 0) {
            mTvRight.setText("移除");
        } else {
            mTvRight.setText("移除(" + count + ")");
        }
    }

    /**
     * 服务器移除粉丝操作
     */
    private void removeFans(String toUserIds) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", toUserIds);

        HttpUtils.post().url(coreManager.getConfig().FRIENDS_FANS_DELETE)
                .params(params)
                .build()
                .execute(new ListCallback<User>(User.class) {
                    @Override
                    public void onResponse(ArrayResult<User> result) {
                        if (result.getResultCode() == 1) {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                            Iterator<User> itr = fansList.iterator();
                            while (itr.hasNext()) {
                                User user = itr.next();
                                if (user.isSelected()) {
                                    //好友移粉需要在关系通知提醒
                                    if (user.getFriends().getStatus() == Friend.STATUS_FRIEND) {
                                        ChatMessage removeChatMessage = new ChatMessage();
                                        removeChatMessage.setContent("你移除" + user.getNickName() + "粉丝，解除好友关系");
                                        removeChatMessage.setTimeSend(TimeUtils.sk_time_current_time());
                                        FriendDao.getInstance().updateLastChatMessage(coreManager.getSelf().getUserId(), Friend.ID_NEW_FRIEND_MESSAGE, removeChatMessage);

                                        NewFriendMessage message = NewFriendMessage.createWillSendMessage(
                                                coreManager.getSelf(), XmppMessage.TYPE_CANCEL_FANS, null, user);

                                        NewFriendDao.getInstance().createOrUpdateNewFriend(message);
                                        NewFriendDao.getInstance().changeNewFriendState(message.getUserId(), Friend.STATUS_31);
                                        ListenerManager.getInstance().notifyNewFriend(coreManager.getSelf().getUserId(), message, true);
                                        FriendDao.getInstance().updateFriendStatus(coreManager.getSelf().getUserId(), message.getUserId(), Friend.STATUS_ATTENTION);

                                        CardcastUiUpdateUtil.broadcastUpdateUi(mContext);
                                    }
                                    adapter.notifyItemRemoved(fansList.indexOf(user));
                                    itr.remove();
                                    updateTitle();
                                    selectCount--;
                                    updateRightTitle(selectCount);
                                    adjustEmpty();
                                }
                            }
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    private void adjustEmpty() {
        if (fansList.size() == 1) {
            //系统的账号
            findViewById(R.id.image_empty).setVisibility(View.VISIBLE);
            findViewById(R.id.tv_empty).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.image_empty).setVisibility(View.GONE);
            findViewById(R.id.tv_empty).setVisibility(View.GONE);
        }
    }

}
